<template>
  <div class="map-box">
    <div class="map-wrapper" ref="MapRef" id="MapRef">
      <div
        @mousemove="handlePlotHoverMove"
        v-if="showPlotHover"
        id="plot-hover"
        class="plot-hover"
        @click="handlePlotAdd"
      >
        <svgIcon :name="mapStore.selectPlottingName" size="50px"></svgIcon>
      </div>
      <div id="plot-container"></div>
    </div>
    <editPanel v-if="!previewMode"></editPanel>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, shallowRef, createApp, onUnmounted } from "vue";
import mapboxgl, { Map, MapMouseEvent, Point, AnySourceData } from "mapbox-gl";

import MapboxDraw from "@mapbox/mapbox-gl-draw";
//@ts-ignore
import DrawRectangle from "mapbox-gl-draw-rectangle-mode";
//@ts-ignore
import StaticMode from "@mapbox/mapbox-gl-draw-static-mode";
import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";
//@ts-ignore
// import CustomDraw from "./customdraw";
import { useEventBus } from "@vueuse/core";
//@ts-ignore
import WKT from "terraformer-wkt-parser";
import { useMapStore } from "@/store/map";
//@ts-ignore
import ContextMenu from "@imengyu/vue3-context-menu";
import editPanel from "../edit-panel/index.vue";
import * as turf from "@turf/turf";
import { useRoute } from "vue-router";
import { ILayer } from "@/struct";
import popupComp from "../popup/index.vue";
import polttingComp from "../popup/plotting.vue";
import MapboxLanguage from "@mapbox/mapbox-gl-language";
import svgIcon from "@/components/svg/index.vue";
// import * as svgtogeojson from "svg-to-geojson/dist/svg-to-geojson.min";
import { pathToCoords } from "./path-to-coordinates";
// import { SRMode, SRCenter, SRStyle } from "mapbox-gl-draw-scale-rotate-mode";
import MapboxDrawer from "@dijiang/front_mapbox_custom_draw";
const layerList = import.meta.glob("@/components/layers/*/index.ts", {
  eager: true,
});
// 注意版本号，与官方最新示例保持一
//@ts-ignore`

const route = useRoute();
const previewMode = ref(false);
const mapStore = useMapStore();
const mapBus = useEventBus("map");
const featureConfigBus = useEventBus("feature.config");
const showPlotHover = ref(true);
let isMove = 0;
let mapDot: any = null;
let drawer;
const popup = new mapboxgl.Popup({
  closeButton: false,
});
mapboxgl.accessToken =
  "pk.eyJ1Ijoic3o2NjY2NjYiLCJhIjoiY2tuam44NXZzMDEwMzJ1cGV3djR6OHA5cCJ9.2LA3YOPHRLTTB25CvAoIdw";
// let customdraw;
let draw: MapboxDraw;
let map: Map;
const MapRef = ref(null);
const props = defineProps({
  pid: {
    type: String,
  },
});
const clearSource = (id: string) => {
  // map.removeLayer("")
  const layers = map.getStyle().layers;
  layers.forEach((item: any) => {
    if (item.source == id) {
      map.removeLayer(item.id);
    }
  });
  if (map.getSource(id)) {
    map.removeSource(id);
  }
};
//
const initMap = () => {
  map = new mapboxgl.Map({
    container: MapRef.value!,
    style: "mapbox://styles/mapbox/dark-v11",
    center: [116.32, 39.89], // 地图起始位置
    zoom: 14, // 地图起始比列
    maxZoom: 18,
  });
  // map.on("style.load", () => {
  //   map?.resize();
  //   mapStore.isLoad = true;
  // });
  map.on("styledata", () => {
    const waiting = () => {
      if (!map.isStyleLoaded()) {
        setTimeout(waiting, 200);
      } else {
        // alert();
        if (!mapStore.isLoad) {
          mapStore.isLoad = true;
          mapStore.datasetInfo.layers.forEach((layer) => {
            clearSource(layer.pid);
            mapBus.emit({
              type: "render.layer",
              value: layer,
            });
          });
          mapBus.emit({
            type: "jumpTo",
            value: {
              //@ts-ignore
              center: mapStore.datasetInfo.location.coordinates,
              zoom: mapStore.datasetInfo.scale,
            },
          });
          // getFeature();
          // addImageList();
          // handleAddSource();
          // handleData()
        }
      }
    };
    waiting();
  });
  draw = new MapboxDraw({
    userProperties: false,
    displayControlsDefault: false, // 不显示默认绘制工具条
    // styles: SRStyle,
    modes: {
      ...MapboxDraw.modes,
      // draw_rectangle: DrawRectangle,
      // static: StaticMode,
      // scaleRotateMode: SRMode,
    },
  });
  map.addControl(
    new MapboxLanguage({
      defaultLanguage: "zh-Hans",
    })
  );

  window["draw"] = draw;
  window["map"] = map;

  map.addControl(draw);
  drawer = new MapboxDrawer(map);
  map.on("mousemove", handleGlobalMouseMove);
  map.on("click", handleGlobalClick);
};

function initListener(cb) {
  //@ts-ignore
  if (map._listeners["draw.create"]) {
    //@ts-ignore
    map._listeners["draw.create"] = undefined;
  }
  //@ts-ignore
  if (map._listeners["draw.update"]) {
    //@ts-ignore
    map._listeners["draw.update"] = undefined;
  }
  //@ts-ignore
  if (map._listeners["draw.delete"]) {
    //@ts-ignore
    map._listeners["draw.delete"] = undefined;
  }
  // 重新初始化监听
  map.on("draw.create", function (e) {
    console.log("draw.create", e, cb);
    if (typeof cb === "function") cb(e.features);
    // 清除之前画出的图形
    // let thisId = e.features[0].id;
    // _this.singleClear(thisId);
  });
  map.on("draw.update", (e) => {
    console.log("draw.update");
    if (typeof cb === "function") cb(e.features);
  });
  map.on("draw.delete", (e) => {
    console.log("draw.delete");
    if (typeof cb === "function") cb(e.features);
  });
}
const eventMap = {
  resize: (e) => {
    map.resize();
  },
  flyTo: (e) => {
    map.flyTo(e.value);
  },
  jumpTo: (e) => {
    map.jumpTo(e.value);
  },
  style: (e) => {
    mapStore.isLoad = false;
    map.setStyle(e.value);
  },
  edit: (e) => {
    const geometry = e.value;
    draw.deleteAll();
    const ids = draw.add(geometry);
    const layer = mapStore.getCurrentLayer();
    if (layer.type == "LineString" || layer.type == "Polygon") {
      draw.changeMode("direct_select", { featureId: ids[0] });
    }

    map.setFilter(`${mapStore.selectLayer}-${layer.type}`, [
      "!=",
      ["get", "pid"],
      e.pid,
    ]);
  },
  "edit.save": (e) => {
    const res = draw.getAll();
    draw.deleteAll();
    featureConfigBus.emit({
      type: "result",
      value: res.features[0],
    });
  },
  "edit.cancel": (e) => {
    draw.deleteAll();
    const layer = mapStore.getCurrentLayer();
    map.setFilter(`${mapStore.selectLayer}-${layer.type}`, true);
  },
  "edit.clear": (e) => {
    draw.deleteAll();
  },
  "render.geojson": (e) => {
    addGeoJson(e.id, e.value);
  },
  "render.layer": (e) => {
    addFromLayer(e.value);
  },

  repaint: (e) => {
    if (!map) {
      return;
    }
    const layer = map.getLayer(e.id);
    if (layer) {
      const properties = e.value;
      for (let key in properties.paint) {
        map.setPaintProperty(e.id, key, properties.paint[key]);
      }
    } else {
      throw Error(`图层:${e.id}不存在`);
    }
    // console.log(e.id + "layer", layer);
  },
  relayout: (e) => {
    const layer = map.getLayer(e.id);
    console.log(e, layer);
    if (layer) {
      const properties = e.value;
      for (let key in properties) {
        map.setLayoutProperty(e.id, key, properties[key]);
      }
    } else {
      // throw Error(`图层:${e.id}不存在`);
    }
  },
  "add.layer": (e) => {
    if (map.getLayer(e.value.id)) {
      map.removeLayer(e.value.id);
    }

    map.addLayer(e.value);
  },
  "draw.point": (e) => {
    draw.changeMode("draw_point");
    initListener(e.callback);
    // map.map.on("draw.update", () => {
    //   alert();
    // });
    // draw.
  },
  "draw.polygon": (e) => {
    draw.changeMode("draw_polygon");
    initListener(e.callback);
    // map.map.on("draw.update", () => {
    //   alert();
    // });
    // draw.
  },
  "draw.lineString": (e) => {
    draw.changeMode("draw_line_string");
    initListener(e.callback);
    // map.map.on("draw.update", () => {
    //   alert();
    // });
    // draw.
  },
  "draw.rectangle": (e) => {
    draw.changeMode("draw_rectangle");
    initListener(e.callback);
    // map.map.on("draw.update", () => {
    //   alert();
    // });
    // draw.
  },
  "draw.doubleArrow": (e) => {
    drawer
      .switchDrawTool("doublearrow", drawer.getStyleTemplate("doublearrow"), {})
      .then((res) => {
        console.log(res);
      });
  },
  "draw.tailsquadarrow": (e) => {
    drawer
      .switchDrawTool(
        "tailsquadarrow",
        drawer.getStyleTemplate("tailsquadarrow"),
        {}
      )
      .then((res) => {
        console.log(res);
      });
  },
  "draw.straightarrow": (e) => {
    drawer
      .switchDrawTool(
        "straightarrow",
        drawer.getStyleTemplate("straightarrow"),
        {}
      )
      .then((res) => {
        console.log(res);
      });
  },
  "draw.text": (e) => {
    console.log(drawer);
    drawer
      .switchDrawTool("text", drawer.getStyleTemplate("text"), {})
      .then((res) => {
        console.log(res);
      });
  },
  "draw.scaleRotate": (e) => {
    // draw.changeMode("scaleRotateMode", {
    //   canScale: true,
    //   canRotate: true, // only rotation enabled
    //   canTrash: false, // disable feature delete
    //   rotatePivot: SRCenter.Center, // rotate around center
    //   scaleCenter: SRCenter.Opposite, // scale around opposite vertex
    //   singleRotationPoint: true, // only one rotation point
    //   rotationPointRadius: 1.2, // offset rotation point
    //   canSelectFeatures: true,
    // });
  },
  ref: (e) => {
    if (e.callback) {
      return e.callback(map);
    }
  },
  marker: (e) => {
    map.flyTo({ center: e.center, zoom: 17 });
    if (mapDot) {
      mapDot.remove();
    }
    const el = document.createElement("div"); //这里可以是任意标签
    el.className = "center-marker";
    // 添加自定义标记点
    //@ts-ignore
    mapDot = new mapboxgl.Marker(el).setLngLat(e.center).addTo(map);
  },
  plot: (e) => {},
};
mapBus.on((e: any) => {
  if (eventMap[e.type]) {
    eventMap[e.type](e);
  }
});
const loadImage = (path: string) => {
  if (!map!.hasImage(path)) {
    map!.loadImage(path, (err, image) => {
      // console.log("load image", image);
      if (!map!.hasImage(path)) {
        map!.addImage(path, image!);
      }
    });
  }
};
const handleClick = (e: any) => {
  const features: any = map?.queryRenderedFeatures(e.point);
  let coordinates = e.features[0].geometry.coordinates.slice();
  mapStore.selectLayer = e.features[0].layer.source;
  // console.log(features, coordinates);
  console.log(features[0]);
  const id = features[0].id;
  console.log(features);
  mapStore.selectFeature = id;
  mapStore.configType = "feature";
  console.log(coordinates);
  if (e.features[0].geometry.type == "Polygon") {
    coordinates = turf.centroid(e.features[0]).geometry.coordinates;
  } else if (e.features[0].geometry.type == "LineString") {
    coordinates = turf.centroid(e.features[0]).geometry.coordinates;
  }
  console.log(coordinates);
  map.easeTo({
    center: coordinates,
    // zoom: 18,
  });
};
const handleMouseMove = (e: any) => {
  map.getCanvas().style.cursor = "pointer";
  // const description =
  //   e.features[0].properties.name || e.features[0].properties.pid;
  // const coordinates = e.features[0].geometry.coordinates.slice();
  // popup.setLngLat(e.lngLat).setText(description).addTo(map);
};
const handleMouseLeave = (e: any) => {
  map.getCanvas().style.cursor = "";
  popup.remove();
};
const handleTouchEnd = (e: any) => {
  const features: any = map?.queryRenderedFeatures(e.point);
  let coordinates = e.features[0].geometry.coordinates.slice();
  mapStore.selectLayer = e.features[0].layer.source;
  const layer = mapStore.getCurrentLayer();
  const pid = features[0].properties["pid"];
  console.log(pid);
  mapStore.selectFeature = pid;
  mapStore.configType = "feature";
  const feature = layer.features.find((item) => item.pid == pid);
  if (e.features[0].geometry.type == "Polygon") {
    coordinates = turf.centroid(e.features[0]).geometry.coordinates;
  } else if (e.features[0].geometry.type == "LineString") {
    coordinates = turf.centroid(e.features[0]).geometry.coordinates;
  }
  map.easeTo({
    center: coordinates,
    // zoom: 18,
  });
  const popupDiv = document.createElement("div");
  const popupApp = createApp(popupComp, {
    feature: feature,
    columns: layer.columns,
    onClose: () => {
      popupDiv.remove();
    },
  });
  popupApp.mount(popupDiv);

  const popup = new mapboxgl.Popup({ anchor: "bottom" })
    .setLngLat(coordinates)
    .setDOMContent(popupDiv)
    .addTo(map);

  // const popup = new
};
const handleGlobalMouseMove = (e: any) => {
  const el = document.getElementById("plot-hover");
  if (el) {
    el.style.left = `${e.point.x}px`;
    el.style.top = `${e.point.y}px`;
  }

  // el.style.transform = `translate(-50)`;
};
const addGeoJson = (id: string, source: AnySourceData) => {
  clearSource(id);
  // map.off("click", id + "-layer", handleClick);
  // map?.off("mouseenter", id + "-layer", handleMouseMove);
  // map?.off("mouseleave", id + "-layer", handleMouseLeave);
  map?.off("mousemove", `${id}-Polygon`, handleMouseMove);
  map?.off("click", `${id}-Polygon`, handleClick);
  map?.off("mouseleave", `${id}-Polygon`, handleMouseLeave);

  map?.off("mousemove", `${id}-Point`, handleMouseMove);
  map?.off("click", `${id}-Point`, handleClick);
  map?.off("mouseleave", `${id}-Point`, handleMouseLeave);

  map?.off("mousemove", `${id}-LineString`, handleMouseMove);
  map?.off("click", `${id}-LineString`, handleClick);
  map?.off("mouseleave", `${id}-LineString`, handleMouseLeave);
  map!.addSource(id, source);
  console.log(source);
  // map.addLayer({})

  map!.addLayer({
    id: `${id}-Point`,
    type: "circle",
    source: id,
    paint: source["data"]["properties"]["style"]?.dotPaint || {
      "circle-color": "#2c9678",
      "circle-radius": 5,
      "circle-stroke-color": "#ddd",
      "circle-stroke-width": 0,
      "circle-blur": 0,
      "circle-stroke-opacity": 0,
      "circle-opacity": 1,
    },
    filter: ["==", ["geometry-type"], "Point"],
    layout: {
      visibility:
        source["data"]["properties"]["layout"]?.visibility == true
          ? "visible"
          : "none" || "none",
    },
  });
  map.addLayer({
    id: `${id}-LineString`,
    type: "line", // 使用线型来表示线
    source: id,
    filter: ["==", ["geometry-type"], "LineString"], // 过滤所有线
    layout: {
      visibility:
        source["data"]["properties"]["layout"]?.visibility == true
          ? "visible"
          : "none" || "none",
    },
    paint: source["data"]["properties"]["style"]?.linePaint || {
      "line-color": "#ff0000",
      "line-width": 5,
    },
  });
  map.addLayer({
    id: `${id}-Polygon`,
    type: "fill", // 使用填充型来表示面
    source: id,
    filter: ["==", ["geometry-type"], "Polygon"], // 过滤所有面
    paint: source["data"]["properties"]["style"]?.polygonPaint || {
      "fill-color": "#2c9678",
    },
    layout: {
      visibility:
        source["data"]["properties"]["layout"]?.visibility == true
          ? "visible"
          : "none" || "none",
    },
  });
  map?.on("mousemove", `${id}-Polygon`, handleMouseMove);
  map?.on("click", `${id}-Polygon`, handleClick);
  map?.on("mouseleave", `${id}-Polygon`, handleMouseLeave);

  map?.on("mousemove", `${id}-Point`, handleMouseMove);
  map?.on("click", `${id}-Point`, handleClick);
  map?.on("mouseleave", `${id}-Point`, handleMouseLeave);

  map?.on("mousemove", `${id}-LineString`, handleMouseMove);
  map?.on("click", `${id}-LineString`, handleClick);
  map?.on("mouseleave", `${id}-LineString`, handleMouseLeave);
  // if(map.getLayer(""))
};
const handleOnMapEvent = (layerId: string) => {
  map?.on("mousemove", layerId, handleMouseMove);
  map?.on("click", layerId, handleClick);
  map?.on("mouseleave", layerId, handleMouseLeave);
  map.on("touchend", layerId, handleTouchEnd);
};
const handleOffMapEvent = (layerId: string) => {
  map?.off("mousemove", layerId, handleMouseMove);
  map?.off("click", layerId, handleClick);
  map?.off("mouseleave", layerId, handleMouseLeave);
  map.off("touchend", layerId, handleTouchEnd);
};
const addFromLayer = (layer: ILayer) => {
  const id = layer.pid;
  const source: AnySourceData = {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: layer.features.map((item) => {
        return {
          type: "Feature",
          id: item.id,
          geometry: item.geometry,
          properties: { name: item.name, ...item.properties },
        };
      }),
      //@ts-ignore
      properties: {
        style: layer.style,
        layout: { visibility: layer.visible },
      },
    },
  };
  clearSource(id);
  map!.addSource(id, source);
  handleOffMapEvent(id);
  layerList[`/src/components/layers/${layer.type}/index.ts`][
    "renderLayerGroup"
  ](id, map, source["data"]["properties"]["style"]);
  // map.addLayer({})
  // if (layer.type == "Point") {
  //   map!.addLayer({
  //     id,
  //     type: "circle",
  //     source: id,
  //     paint: source["data"]["properties"]["style"]?.paint || {
  //       "circle-color": "#2c9678",
  //       "circle-radius": 5,
  //       "circle-stroke-color": "#ddd",
  //       "circle-stroke-width": 0,
  //       "circle-blur": 0,
  //       "circle-stroke-opacity": 0,
  //       "circle-opacity": 1,
  //     },
  //     filter: ["==", ["geometry-type"], "Point"],
  //     layout: {
  //       visibility:
  //         source["data"]["properties"]["layout"]?.visibility == true
  //           ? "visible"
  //           : "none" || "none",
  //     },
  //   });
  // } else if (layer.type == "LineString") {
  //   map.addLayer({
  //     id: `${id}-LineString`,
  //     type: "line", // 使用线型来表示线
  //     source: id,
  //     filter: ["==", ["geometry-type"], "LineString"], // 过滤所有线
  //     layout: {
  //       visibility:
  //         source["data"]["properties"]["layout"]?.visibility == true
  //           ? "visible"
  //           : "none" || "none",
  //       "line-cap": "round",
  //       "line-join": "round",
  //     },
  //     paint: source["data"]["properties"]["style"]?.paint || {
  //       "line-color": "#ff0000",
  //       "line-width": 5,
  //     },
  //   });
  //   // map.addLayer({
  //   //   type: "line",
  //   //   source: id,
  //   //   id: `${id}-LineString-2`,
  //   //   layout: {
  //   //     "line-join": "round",
  //   //   },
  //   //   paint: {
  //   //     "line-color": "rgb(225,213,50)",
  //   //     "line-width": 6,
  //   //     "line-dasharray": [0, 4, 3],
  //   //   },
  //   // });
  //   // const dashArraySequence = [
  //   //   [0, 4, 3],
  //   //   [0.5, 4, 2.5],
  //   //   [1, 4, 2],
  //   //   [1.5, 4, 1.5],
  //   //   [2, 4, 1],
  //   //   [2.5, 4, 0.5],
  //   //   [3, 4, 0],
  //   //   [0, 0.5, 3, 3.5],
  //   //   [0, 1, 3, 3],
  //   //   [0, 1.5, 3, 2.5],
  //   //   [0, 2, 3, 2],
  //   //   [0, 2.5, 3, 1.5],
  //   //   [0, 3, 3, 1],
  //   //   [0, 3.5, 3, 0.5],
  //   // ];

  //   // let step = 0;

  //   // function animateDashArray(timestamp: number) {
  //   //   // Update line-dasharray using the next value in dashArraySequence. The
  //   //   // divisor in the expression `timestamp / 50` controls the animation speed.
  //   //   //@ts-ignore
  //   //   const newStep = parseInt((timestamp / 50) % dashArraySequence.length);

  //   //   if (newStep !== step) {
  //   //     map.setPaintProperty(
  //   //       `${id}-LineString-2`,
  //   //       "line-dasharray",
  //   //       dashArraySequence[step]
  //   //     );
  //   //     step = newStep;
  //   //   }

  //   //   // Request the next frame of the animation.
  //   //   requestAnimationFrame(animateDashArray);
  //   // }

  //   // // start the animation
  //   // animateDashArray(0);
  //   // let offset = 0;
  //   // layer["enableAnimation"] = true;
  //   // layer["animation"] = () => {
  //   //   offset = (offset + 1) % 4;
  //   //   // layer.style.paint;
  //   //   if (map) {
  //   //     map.setPaintProperty(`${id}-LineString`, "line-dashoffset", offset);
  //   //   }
  //   //   if (layer["enableAnimation"]) {
  //   //     requestAnimationFrame(layer["animation"]);
  //   //   }
  //   // };
  //   // layer["animation"]();
  // } else if (layer.type == "Polygon") {
  //   map.addLayer({
  //     id: `${id}-Polygon`,
  //     type: "fill", // 使用填充型来表示面
  //     source: id,
  //     filter: ["==", ["geometry-type"], "Polygon"], // 过滤所有面
  //     paint: source["data"]["properties"]["style"]?.paint || {
  //       "fill-color": "#2c9678",
  //     },
  //     layout: {
  //       visibility:
  //         source["data"]["properties"]["layout"]?.visibility == true
  //           ? "visible"
  //           : "none" || "none",
  //     },
  //   });
  // } else if (layer.type == "Symbol") {
  //   loadImage(
  //     "https://rcs-bucket.oss-cn-hangzhou.aliyuncs.com/app%2Fspace%2F78373e955caf4eb8a3a82b36e7d971f6_img-1.png"
  //   );
  //   map.addLayer({
  //     id: `${id}-Symbol`,
  //     type: "symbol", // 使用填充型来表示面
  //     source: id,
  //     paint: {
  //       "text-color": "#ffffff",
  //       "icon-color": "#fff",
  //       "icon-halo-color": "#000",
  //       "icon-halo-width": 4,
  //       "icon-halo-blur": 0.5,
  //     },
  //     layout: {
  //       "icon-image":
  //         "https://rcs-bucket.oss-cn-hangzhou.aliyuncs.com/app%2Fspace%2F78373e955caf4eb8a3a82b36e7d971f6_img-1.png",
  //       "text-field": ["get", "name"],
  //       "icon-size": 0.3,
  //       "icon-allow-overlap": false,
  //       "text-allow-overlap": false,
  //       "icon-offset": [0, -80],
  //       "text-size": 14,
  //       visibility:
  //         source["data"]["properties"]["layout"]?.visibility == true
  //           ? "visible"
  //           : "none" || "none",
  //     },
  //   });
  // }
  handleOnMapEvent(id);
};
const handleShowContextMenu = (e: MouseEvent) => {
  e.preventDefault();
  console.log("right click");
  ContextMenu.showContextMenu({
    x: e.x,
    y: e.y,
    theme: "flat dark",
    items: [
      {
        label: "创建点",
      },
      {
        label: "创建线段",
      },
      {
        label: "创建面",
      },
    ],
  });
};
const handlePlotHoverMove = (e: any) => {
  if (showPlotHover.value) {
    const el = document.getElementById("plot-hover");
    const event = {};
    event["point"] = {
      x: el.offsetLeft + e.offsetX - 26,
      y: el.offsetTop + e.offsetY - 26,
    };
    event["featureTarget"] = undefined;
    event["originalEvent"] = e;
    event["target"] = map;
    // console.log(e.point);
    map.fire("mousemove", event);
  }

  // e.stopPropagation();
  // e.preventDefault();
};
const buildFeature = (data) => {
  const { path, coords } = data;

  let feature = {
    type: "Feature",
    properties: {},
    geometry: {},
  };

  if (path.id) {
    feature.properties["id"] = path.id;
  }

  if (path.getAttribute("fill")) {
    feature.properties["fill"] = path.getAttribute("fill");
  }

  // If the first and last coords match it should be drawn as a polygon
  if (
    coords[0][0] === coords[coords.length - 1][0] &&
    coords[0][1] === coords[coords.length - 1][1]
  ) {
    feature.geometry = {
      type: "Polygon",
      coordinates: [
        coords.map((d) => {
          const c = map.unproject(d);
          return [c.lng, c.lat];
        }),
      ],
    };
  } else {
    const getSum = (total, num) => {
      return total + num;
    };
    try {
      // try to see if it should be a multipolygon
      let distances = [];
      let splits = [];
      coords.forEach((c, idx) => {
        if (idx > 0) {
          const from = turf.point([
            map.unproject(coords[idx - 1])["lng"],
            map.unproject(coords[idx - 1])["lat"],
          ]);
          const to = turf.point([
            map.unproject(c)["lng"],
            map.unproject(c)["lat"],
          ]);
          const options = { units: "miles" };

          const distance = turf.distance(from, to, options);
          // get distances between points
          distances.push(distance);
        }
      });

      const distAvg = distances.reduce(getSum) / distances.length;
      coords.forEach((c, idx) => {
        if (idx > 0) {
          const from = turf.point([
            map.unproject(coords[idx - 1])["lng"],
            map.unproject(coords[idx - 1])["lat"],
          ]);
          const to = turf.point([
            map.unproject(c)["lng"],
            map.unproject(c)["lat"],
          ]);
          const options = { units: "miles" };
          const distance = turf.distance(from, to, options);
          // if the following coordinate is ~2.5 farther away than average, it is most likely a new polygon
          if (distance > distAvg * 2.5) {
            splits.push(idx);
          }
        }
      });

      // idx only gets to last split - needs to get to the end of the shape
      splits.push(250);

      let newShapeArray = [];
      splits.forEach((s, idx) => {
        let shape = [];
        if (idx === 0) {
          for (let i = 0; i < s; i++) {
            shape.push([
              map.unproject(coords[i])["lng"],
              map.unproject(coords[i])["lat"],
            ]);
          }
        } else {
          for (let i = splits[idx - 1]; i < s; i++) {
            shape.push([
              map.unproject(coords[i])["lng"],
              map.unproject(coords[i])["lat"],
            ]);
          }
        }
        newShapeArray.push([shape]);
      });

      newShapeArray.forEach((shape) => {
        shape[0].push(shape[0][0]);
      });

      feature.geometry = {
        type: "MultiPolygon",
        coordinates: newShapeArray,
      };
    } catch (err) {
      console.log(err);
      feature.geometry = {
        type: "LineString",
        coordinates: coords.map((d) => {
          const c = map.unproject(d);
          return [c.lng, c.lat];
        }),
      };
    }
  }

  return feature;
};
const mergeFeature = (features: any) => {
  const feature = {
    type: "Feature",
    properties: {},
    geometry: {},
  };
};
const handlePlotAdd = (e) => {
  const el = document.getElementById("plot-hover");
  const topLeft = map.unproject([el.offsetLeft, el.offsetTop]);
  const bottomRight = map.unproject([
    el.offsetLeft + el.clientWidth,
    el.offsetTop + el.clientHeight,
  ]);
  // const svg = el.getElementsByTagName("svg")[0];
  const parser = new DOMParser();
  const doc = parser.parseFromString(mapStore.selectPlottingIcon, "text/html");
  console.log(doc);
  const svg = doc.body.firstChild;
  // console.log(el.clientWidth, el.clientHeight, el.clientLeft);
  console.log([topLeft.toArray(), bottomRight.toArray()], svg, 3);
  //@ts-ignore
  const paths = svg.querySelectorAll("path");
  console.log(paths);
  if (!paths.length) {
    alert("未发现任何path");
    // this.setState({
    //   helpText: 'No paths were found in this SVG'
    // });
    return;
  }
  const data = Array.from(paths)
    .map((path) => pathToCoords(path, 0.05, 50, el.offsetLeft, el.offsetTop))
    .map(buildFeature)
    .map((item: any) => {
      console.log(item);
      draw.add(item);
      // draw.getSelected();
      // map.fire("click", e);
    });
  const editLayers = draw.getAll();
  console.log(editLayers);
  const editLayersName = editLayers.features.map((item) => item.id as string);
  console.log(editLayersName);
  // draw.changeMode("simple_select", {
  //   // featureIds: [editLayers.features[0].id as string],
  //   featureIds: editLayersName,
  // });

  // draw.changeMode("scaleRotateMode", {
  //   canScale: true,
  //   canRotate: true, // only rotation enabled
  //   canTrash: false, // disable feature delete

  //   rotatePivot: SRCenter.Center, // rotate around center
  //   scaleCenter: SRCenter.Opposite, // scale around opposite vertex

  //   singleRotationPoint: true, // only one rotation point
  //   rotationPointRadius: 1.2, // offset rotation point

  //   canSelectFeatures: true,
  // });
  // console.log(
  //   svgtogeojson.svgtogeojson.svgToGeoJson(
  //     [topLeft.toArray(), bottomRight.toArray()],
  //     svg[0],
  //     3
  //   )
  // );
};
// const createPlotHoverEl = ()=>{
//   document
// }
const handleGlobalClick = (e) => {
  // console.log(e);
  // const popupDiv = document.createElement("div");
  // popupDiv.className = "pop-marker";
  // const popupApp = createApp(polttingComp, {
  //   onClose: () => {
  //     // popupDiv.remove();
  //   },
  // });
  // popupApp.mount(popupDiv);
  // new mapboxgl.Marker(popupDiv, { anchor: "center" })
  //   .setLngLat(e.lngLat)
  //   .addTo(map);
  // const;
  // container.appendChild()
};
watch(
  () => mapStore.selectPlottingName,
  (val: string) => {
    if (val) {
      showPlotHover.value = true;
    } else {
      showPlotHover.value = false;
    }
  },
  {
    immediate: true,
  }
);
onMounted(() => {
  // console.log(route.name);
  if (route.name == "preview") {
    previewMode.value = true;
  }
  initMap();
  // console.log()
});
onUnmounted(() => {
  if (map) {
    map.off("click", handleGlobalClick);
    map.off("mousemove", handleGlobalMouseMove);
  }
});
</script>

<style lang="scss" scoped>
.map-box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}
.map-wrapper {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: absolute;
}
</style>
<style>
.mapboxgl-popup {
  max-width: 400px;
  position: absolute;
  background-color: #fff;
  z-index: 100;
  left: 0px;
  top: -20px;
  border-radius: 4px;
  filter: drop-shadow(0px 0px 10px #2c967833);
  padding: 4px;
  font-size: 12px;
  color: #444;
}
.center-marker {
  width: 10px;
  height: 10px;
  background-color: orange;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  border-radius: 20px;
  border: 2px solid #fff;
  position: absolute;
  left: 0px;
  top: 0px;
}
.plot-hover {
  width: 50px;
  height: 50px;
  /* background-color: #fff; */
  opacity: 0.8;
  position: absolute;
  left: 0px;
  top: 0px;
  /* transform: translate(-50%, -50%); */
}
.pop-marker {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0px;
  top: 0px;
}
</style>
